<template>
  <!-- 医院详情页面 -->
  <div class="hospital-detail-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <span class="header-title">医院详情</span>
      </div>
      <div class="header-right">
        <el-button @click="goBack">返回</el-button>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container" v-loading="loading">
      <div class="loading-text">正在加载医院详情...</div>
    </div>

    <!-- 详情内容 -->
    <div v-else class="detail-content">
      <!-- 基本信息卡片 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">基本信息</span>
          </div>
        </template>
        
        <div class="basic-info">
          <!-- 左侧图片 -->
          <div class="hospital-image">
            <img 
              v-if="hospitalDetail.coverImageUrl" 
              :src="hospitalDetail.coverImageUrl" 
              alt="医院图片"
              class="cover-image"
            />
            <div v-else class="no-image">
              <el-icon class="no-image-icon"><Picture /></el-icon>
              <span>暂无图片</span>
            </div>
          </div>
          
          <!-- 右侧信息表格 -->
          <div class="info-table">
            <table class="detail-table">
              <tr>
                <td class="label">ID</td>
                <td class="value">{{ hospitalDetail.id || '-' }}</td>
                <td class="label">医院名称</td>
                <td class="value">{{ hospitalDetail.name || '-' }}</td>
              </tr>
              <tr>
                <td class="label">是否推荐</td>
                <td class="value">
                  <el-tag :type="hospitalDetail.status ? 'success' : 'info'">
                    {{ hospitalDetail.status ? '是' : '否' }}
                  </el-tag>
                </td>
                <td class="label">医生人数</td>
                <td class="value">{{ hospitalDetail.doctorNumber || '-' }}</td>
              </tr>
              <tr>
                <td class="label">科室数</td>
                <td class="value">{{ hospitalDetail.departmentsNumber || '-' }}</td>
                <td class="label">所在地区</td>
                <td class="value">{{ getLocationFromAddress(hospitalDetail.address) }}</td>
              </tr>
              <tr>
                <td class="label">详细地址</td>
                <td class="value">{{ hospitalDetail.address || '-' }}</td>
                <td class="label">医院电话</td>
                <td class="value">{{ hospitalDetail.phone || '-' }}</td>
              </tr>
            </table>
          </div>
        </div>
      </el-card>

      <!-- 科室信息卡片 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">科室</span>
          </div>
        </template>
        
        <div class="departments-section">
          <div v-if="departmentsByCategory && Object.keys(departmentsByCategory).length > 0">
            <div v-for="(departments, category) in departmentsByCategory" :key="category" class="department-category">
              <h3 class="category-title">{{ category }}</h3>
              <div class="department-tags">
                <el-tag 
                  v-for="dept in departments" 
                  :key="dept" 
                  class="department-tag"
                  type="info"
                >
                  {{ dept }}
                </el-tag>
              </div>
            </div>
          </div>
          <div v-else class="no-departments">
            <span>暂无科室信息</span>
          </div>
        </div>
      </el-card>

      <!-- 简介信息卡片 -->
      <el-card class="info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span class="card-title">简介</span>
          </div>
        </template>
        
        <div class="introduction-section">
          <div v-if="hospitalDetail.introduction" class="introduction-content">
            {{ hospitalDetail.introduction }}
          </div>
          <div v-else class="no-introduction">
            <span>暂无医院介绍</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getHospitalDetail, getDepartments } from '@/HTTPS/server';
import { ElMessage } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';

// 路由实例
const route = useRoute();
const router = useRouter();

// 加载状态
const loading = ref(true);

// 医院详情数据
const hospitalDetail = reactive({
  id: '',
  name: '',
  level: '',
  address: '',
  phone: '',
  doctorNumber: '',
  departmentsNumber: '',
  status: false,
  createTime: '',
  coverImageUrl: '',
  introduction: '',
  departmentsId: ''
});

// 科室数据
const departmentList = ref<any[]>([]);

// 根据科室ID获取科室名称并分类
const departmentsByCategory = computed(() => {
  if (!hospitalDetail.departmentsId || departmentList.value.length === 0) {
    return {};
  }

  let departmentIds: number[] = [];
  if (typeof hospitalDetail.departmentsId === 'string') {
    departmentIds = hospitalDetail.departmentsId.split(',').map((id: string) => parseInt(id.trim())).filter((id: number) => !isNaN(id));
  } else if (typeof hospitalDetail.departmentsId === 'number') {
    departmentIds = [hospitalDetail.departmentsId];
  }

  const categorizedDepartments: Record<string, string[]> = {};

  departmentList.value.forEach(dept => {
    if (departmentIds.includes(dept.values)) {
      if (!categorizedDepartments[dept.label]) {
        categorizedDepartments[dept.label] = [];
      }
    }
    if (dept.children && dept.children.length > 0) {
      dept.children.forEach((subDept: any) => {
        if (departmentIds.includes(subDept.values)) {
          if (!categorizedDepartments[dept.label]) {
            categorizedDepartments[dept.label] = [];
          }
          categorizedDepartments[dept.label].push(subDept.label);
        }
      });
    }
  });

  return categorizedDepartments;
});

// 从地址中提取地区信息
const getLocationFromAddress = (address: string) => {
  if (!address) return '-';
  // 简单的地区提取逻辑，可以根据实际需求调整
  const match = address.match(/^([^市]+市|[^区]+区|[^县]+县)/);
  return match ? match[1] : address.split(' ')[0] || '-';
};

// 获取科室数据
const loadDepartments = async () => {
  try {
    const res = await getDepartments();
    if (res.data.code === 200 && res.data.data) {
      departmentList.value = res.data.data;
    }
  } catch (error) {
    console.error('获取科室数据失败:', error);
  }
};

// 获取医院详情
const loadHospitalDetail = async () => {
  const hospitalId = route.params.id;
  if (!hospitalId) {
    ElMessage.error('医院ID不能为空');
    goBack();
    return;
  }

  try {
    loading.value = true;
    console.log('正在获取医院详情，ID:', hospitalId);
    
    // 使用医院列表API，通过分页大小为1来获取单个医院
    // 由于后端没有单独的获取医院详情API，我们使用列表API并过滤结果
    const res = await getHospitalDetail({ 
      pageIndex: 1, 
      pageSize: 100  // 获取足够多的数据以便查找
    });
    console.log('医院列表API响应:', res);
    
    if (res.data.code === 200 && res.data.data && res.data.data.list) {
      // 从列表中找到对应ID的医院
      const hospitalList = res.data.data.list;
      const targetHospital = hospitalList.find((hospital: any) => hospital.id == hospitalId);
      
      if (targetHospital) {
        hospitalDetail.id = targetHospital.id || '';
        hospitalDetail.name = targetHospital.name || '';
        hospitalDetail.level = targetHospital.level || '';
        hospitalDetail.address = targetHospital.address || '';
        hospitalDetail.phone = targetHospital.phone || '';
        hospitalDetail.doctorNumber = targetHospital.doctorNumber || '';
        hospitalDetail.departmentsNumber = targetHospital.departmentsNumber || '';
        hospitalDetail.status = targetHospital.status || false;
        hospitalDetail.createTime = targetHospital.createTime || '';
        hospitalDetail.coverImageUrl = targetHospital.coverImageUrl || '';
        hospitalDetail.introduction = targetHospital.introduction || '';
        hospitalDetail.departmentsId = targetHospital.departmentsId || '';
        
        console.log('医院详情数据已加载:', hospitalDetail);
      } else {
        ElMessage.error('未找到指定的医院信息');
        goBack();
      }
    } else {
      ElMessage.error(res.data.message || '获取医院详情失败');
      goBack();
    }
  } catch (error) {
    console.error('获取医院详情失败:', error);
    ElMessage.error('获取医院详情失败，请检查网络连接或重新登录');
    // 不立即返回，给用户选择的机会
  } finally {
    loading.value = false;
  }
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 页面初始化
onMounted(async () => {
  console.log('医院详情页面初始化，路由参数:', route.params);
  await loadDepartments();
  await loadHospitalDetail();
});
</script>

<style scoped>
.hospital-detail-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  background-color: #ffffff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.loading-text {
  color: #606266;
  font-size: 14px;
}

.detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card {
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.basic-info {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.hospital-image {
  flex-shrink: 0;
  width: 240px;
  height: 180px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e4e7ed;
}

.cover-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.no-image {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
  color: #909399;
}

.no-image-icon {
  font-size: 48px;
  margin-bottom: 8px;
}

.info-table {
  flex: 1;
}

.detail-table {
  width: 100%;
  border-collapse: collapse;
}

.detail-table td {
  padding: 12px 16px;
  border: 1px solid #e4e7ed;
  vertical-align: middle;
}

.detail-table .label {
  background-color: #f8f9fa;
  font-weight: 500;
  color: #606266;
  width: 120px;
  text-align: center;
}

.detail-table .value {
  color: #303133;
  min-width: 150px;
}

.departments-section {
  min-height: 100px;
}

.department-category {
  margin-bottom: 20px;
}

.department-category:last-child {
  margin-bottom: 0;
}

.category-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 12px 0;
  padding-bottom: 8px;
  border-bottom: 2px solid #409eff;
}

.department-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.department-tag {
  margin: 0;
}

.no-departments {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  color: #909399;
  font-size: 14px;
}

.introduction-section {
  min-height: 120px;
}

.introduction-content {
  line-height: 1.8;
  color: #303133;
  font-size: 14px;
  text-align: justify;
}

.no-introduction {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 80px;
  color: #909399;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .basic-info {
    flex-direction: column;
    gap: 20px;
  }
  
  .hospital-image {
    width: 100%;
    max-width: 300px;
    margin: 0 auto;
  }
  
  .detail-table .label {
    width: 100px;
    font-size: 12px;
  }
  
  .detail-table td {
    padding: 8px 12px;
  }
}
</style>